<?php
/**
 * Created by PhpStorm.
 * User: Lyq
 * Date: 2018/8/22
 * Time: 上午8:21
 */
namespace app\admin\controller;

use app\admin\model\Wallet;
use think\Exception;
use think\Db;

class Active extends Common
{
    //活动资源列表
    public function index()
    {
        $this->templateTitle('资源活动列表');
        $this->assign('status_list',get_active_status('',2));
        //判断条件
        $where['ac.id']=['gt',0];

        $pro = trim(input('pro'));
        $this->assign('area_province',$pro);
        if($pro){
            $where['ac.pro'] = $pro;
        }

        $city = trim(input('city'));
        $this->assign('area_city',$city);
        if($city){
            $where['ac.city'] = $city;
        }

        //搜索条件-用户
        $user_condition = request()->param("user_condition");
        $this->assign("user_condition", $user_condition);
        if ($user_condition)
        {
            $where["us.real_name|us.mobile|us.id"] = $user_condition;
        }

        //搜索条件-联盟商
        $un_condition = request()->param("un_condition");
        $this->assign("un_condition", $un_condition);
        if ($un_condition)
        {
            $where["un.title|un.id"] = $un_condition;
        }

        //搜索条件-主题
        $condition = request()->param("condition");
        $this->assign("condition", $condition);
        if ($condition)
        {
            $where["ac.title"] = ["LIKE", "%$condition%"];
        }

        //H链结算状态
        $status = request()->param('status');
        $this->assign('status',$status);
        if($status!=''){
            $where['ac.status'] = $status;
        }

        //搜索条件-活动期限
        if (request()->has("time_range"))
        {
            //解析时间
            $timeRange = request()->param("time_range");
            $timeRange = explode(" ~ ", $timeRange);
            //模板渲染值
            $this->assign("range_start", ["time_range" => $timeRange[0]]);
            $this->assign("range_end", ["time_range" => $timeRange[1]]);

            $where['ac.begintime'] = ["EGT", strtotime($timeRange[0] . " 00:00:00")];
            $where['ac.endtime'] = ["ELT", strtotime($timeRange[1] . " 00:00:00")];
        }
        else
        {
            //模板渲染值
            $this->assign("range_start", ["time_range" => '1970-01-01']);
            $this->assign("range_end", ["time_range" => date("Y-m-d")]);
        }

        //获取活动列表
        $list = Db::name("active")
            ->alias('ac')
            ->join('__USER__ us','us.id=ac.uid','LEFT')
            ->join('__UNION__ un','un.id=ac.union_id','LEFT')
            ->where($where)
            ->order("ac.display_order DESC,ac.update_time DESC")
            ->field('ac.*,us.real_name as uname,us.mobile as umobile,un.title as untitle')
            ->paginate(10);
        $this->assign("list", $list);

        return $this->fetch();
    }

    //添加活动
    public function add()
    {
        if (request()->isGet())
        {
            $this->layoutModal();
            $this->assign('category_list',get_active_type('',2));
            $this->assign("range_start", ["time_range" => date("Y-m-d")]);
            $this->assign("range_end", ["time_range" => date("Y-m-d H:i")]);
            $this->assign("range_start2", ["time_rangeone" => date("Y-m-d H:i")]);
            return $this->fetch();
        }

        if (request()->isAjax())
        {
            //创建数据
            $data = array(
                "create_time" => now_datetime(),
                "update_time" => now_datetime(),
            );
            $data['pro'] = request()->param("pro");
            if(empty($data['pro'])){
                return $this->ajaxError('请选择省份');
            }
            $data['city'] = request()->param("city");
            if(empty($data['city'])){
                return $this->ajaxError('请选择城市');
            }

            //所属会员
            $data["uid"] = request()->param("uid");
            if(empty($data['uid'])){
                return $this->ajaxError('请输入会员ID');
            }

            $data["union_id"] = request()->param("union_id");
            if(empty($data['union_id'])){
                return $this->ajaxError('请选择承办联盟商');
            }
            $union = Db::name('union')->where('id',$data['union_id'])->find();
            if(!$union||$union['in_blacklist']==1){
                return $this->ajaxError('此联盟商不存在或已拉黑无法作为承办联盟商');
            }
            //活动类型
//            $data["type"] = request()->param("type");
//            if(empty($data['type'])){
//                return $this->ajaxError('请选择活动类型');
//            }

            //活动期限
            $timeRange = request()->param('time_range');
            $timeRange = explode(" ~ ", $timeRange);
            if(empty($timeRange[0])||empty($timeRange[1])||strtotime($timeRange[0])>strtotime($timeRange[1])){
                return $this->ajaxError('请正确输入活动期限');
            }
            $data['begintime'] = strtotime($timeRange[0]);
            $data['endtime'] = strtotime($timeRange[1]);

            //报名截止日期
            $timeRangeone = request()->param('time_rangeone');
            if(empty($timeRangeone)){
                return $this->ajaxError('请输入报名截止日期');
            }
            $data['signstop_time'] = strtotime($timeRangeone);

            //活动主题
            $data["title"] = request()->param("title");
            if(empty($data['title'])){
                return $this->ajaxError('请输入活动主题');
            }

            //缩略图
            $data["thumb"] = request()->param("thumb");
            if(empty($data['thumb'])){
                return $this->ajaxError('请上传缩略图');
            }

            //背景图片
            $data["background"] = request()->param("background");
            if(empty($data['background'])){
                return $this->ajaxError('请上传背景图片');
            }

            //H币
            $data['coin'] = request()->param('coin');
            if($data['coin']<config('pay_config.coin_min')){
                return $this->ajaxError('H链币费用不得少于'.(string)config('pay_config.coin_min'));
            }
            //现金
            $data['money'] = request()->param('money');
            if($data['money']<config('pay_config.money_min')){
                return $this->ajaxError('现金费用不得少于'.(string)config('pay_config.money_min'));
            }

            //详细地址
            $data["address"] = request()->param("address");
            //排序
            $data["display_order"] = request()->param("order");
            $data["is_visible"] = request()->param("visible");
            $data["is_recommend"] = request()->param("recommend");
            //详情
            $detail = request()->param("article_detail");
            $data["detail"] = $detail;

            try
            {
                $save = Db::name("active")->insert($data);
                if($save){
                    $this->ajaxSuccess('活动添加成功');
                }else{
                    $this->ajaxError('服务器繁忙，请稍后再试');
                }
            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //编辑活动
    public function edit()
    {
        //活动ID
        $id = request()->param("id");

        //获取活动
        $info = Db::name("active")
            ->where("id", $id)
            ->find();

        if (request()->isGet())
        {
            $this->layoutModal();


            $this->assign("info", $info);

            $this->assign('category_list',get_active_type('',2));
            //活动期限
            $this->assign("range_start", ["time_range" => date("Y-m-d H:i",$info['begintime'])]);
            $this->assign("range_end", ["time_range" => date("Y-m-d H:i",$info['endtime'])]);
            //报名截止
            $this->assign("range_start2", ["time_rangeone" => date("Y-m-d H:i",$info['signstop_time'])]);

            //处理图片
            $this->assign("single_image", array("thumb"=>$info["thumb"],"background"=>$info['background']));
            //处理详细内容
            $this->assign("ueditor_content", array("article_detail"=>$info["detail"]));
            //处理地区
            $this->assign("area_province", $info['pro']);
            $this->assign("area_city", $info['city']);
            //会员
            $this->assign('user_id',$info['uid']);
            //联盟商
            $this->assign('union_id', $info['union_id']);

            return $this->fetch();
        }

        if (request()->isAjax())
        {
            if($info['status']!=0){
                return $this->ajaxError('活动已完成结算视为结束，禁止编辑');
            }
            //创建数据
            $data = array(
                "update_time" => now_datetime(),
            );
            $data['pro'] = request()->param("pro");
            if(empty($data['pro'])){
                return $this->ajaxError('请选择省份');
            }
            $data['city'] = request()->param("city");
            if(empty($data['city'])){
                return $this->ajaxError('请选择城市');
            }

            //所属会员
            $data["uid"] = request()->param("uid");
            if(empty($data['uid'])){
                return $this->ajaxError('请输入会员ID');
            }

            $data["union_id"] = request()->param("union_id");
            if(empty($data['union_id'])){
                return $this->ajaxError('请选择承办联盟商');
            }
            $union = Db::name('union')->where('id',$data['union_id'])->find();
            if(!$union||$union['in_blacklist']==1){
                return $this->ajaxError('此联盟商不存在或已拉黑无法作为承办联盟商');
            }
            //活动类型
//            $data["type"] = request()->param("type");
//            if(empty($data['type'])){
//                return $this->ajaxError('请选择活动类型');
//            }

            //活动期限
            $timeRange = request()->param('time_range');
            $timeRange = explode(" ~ ", $timeRange);
            if(empty($timeRange[0])||empty($timeRange[1])||strtotime($timeRange[0])>strtotime($timeRange[1])){
                return $this->ajaxError('请正确输入活动期限');
            }
            $data['begintime'] = strtotime($timeRange[0]);
            $data['endtime'] = strtotime($timeRange[1]);

            //报名截止日期
            $timeRangeone = request()->param('time_rangeone');
            if(empty($timeRangeone)){
                return $this->ajaxError('请输入报名截止日期');
            }
            $data['signstop_time'] = strtotime($timeRangeone);

            //活动主题
            $data["title"] = request()->param("title");
            if(empty($data['title'])){
                return $this->ajaxError('请输入活动主题');
            }

            //缩略图
            $data["thumb"] = request()->param("thumb");
            if(empty($data['thumb'])){
                return $this->ajaxError('请上传缩略图');
            }

            //背景图片
            $data["background"] = request()->param("background");
            if(empty($data['background'])){
                return $this->ajaxError('请上传背景图片');
            }

            //H币
            $data['coin'] = request()->param('coin');
            if($data['coin']<config('pay_config.coin_min')){
                return $this->ajaxError('H链币费用不得少于'.(string)config('pay_config.coin_min'));
            }
            //现金
            $data['money'] = request()->param('money');
            if($data['money']<config('pay_config.money_min')){
                return $this->ajaxError('现金费用不得少于'.(string)config('pay_config.money_min'));
            }

            //详细地址
            $data["address"] = request()->param("address");
            //排序
            $data["display_order"] = request()->param("order");
            $data["is_visible"] = request()->param("visible");
            $data["is_recommend"] = request()->param("recommend");
            //详情
            $detail = request()->param("article_detail");
            $data["detail"] = $detail;


            try
            {
                $save = Db::name("active")
                    ->where("id", $id)
                    ->update($data);
                if($save){

                    $this->ajaxSuccess('活动编辑成功');
                }else{
                    $this->ajaxError('活动编辑失败');
                }
            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //推荐活动
    public function recommend()
    {
        if (request()->isAjax())
        {
            //活动ID
            $activeid = request()->param("aid");
            //推荐状态
            $status = request()->param("status");

            //更新活动
            Db::name("active")
                ->where("id", $activeid)
                ->update(array(
                    "is_recommend" => $status,
                    "update_time" => now_datetime(),
                ));

            $this->ajaxSuccess('推荐状态修改成功');
        }
    }

    //删除活动
    public function remove()
    {
        if (request()->isAjax())
        {
            //活动ID
            $id = request()->param("id");
            $this->ajaxSuccess('处理流程最后做要考虑订单等');
            try
            {

            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    /**
     *活动的订单H链结算
     */
    public function settleAccounts(){
        if(request()->isAjax()){
            ob_clean();
            header("Content-type:text/html;Charset=utf-8");
            ini_set('memory_limit','100M');    // 临时设置最大内存占用为100M
            set_time_limit(0);   // 设置脚本最大执行时间 为0 永不过期

            $id = intval(request()->param('id'));
            if(empty($id)){
                return $this->ajaxError('参数有误');
            }

            $active = Db::name('active')->where('id',$id)->find();
            if(!$active){
                return $this->ajaxError('活动不存在或已删除');
            }

            if($active['status']==1){
                return $this->ajaxError('活动已经结算，禁止重复结算');
            }

            $time = time();
            if($active['endtime']>$time){
                return $this->ajaxError('活动未到结束时间，暂不可结算');
            }

            $order = Db::name('order')
                ->alias('or')
                ->join('__ORDER_COMMENT__ oc','or.id=oc.order_id','LEFT')
                ->join('__USER__ us','us.id=or.receive_uid','LEFT')
                ->where('or.order_type',2)
                ->where('or.active_id',$id)
                ->where('or.pay_status',1)
                ->where('or.count_status',0)
                ->field('or.*,oc.star as star,us.mobile as mobile')
                ->select();
            if(count($order)>0){
                $nums = 1;
                foreach($order as $item){
                    //计算结算
                    $star = empty($item['star']) ? 5 : $item['star'];
                    $addcoin = $item['coin']*$star/5;
                    $addcoin = round($addcoin,8);
                    $coin_cut = $item['coin']-$addcoin;
                    $data = [
                        'count_status'=>1,
                        'coin_cut'=>$coin_cut,
                        'is_comment'=>2,
                    ];

                    Db::name('order')->where('id',$item['id'])->update($data);

                    if($addcoin>0 && !empty($item['mobile'])){
                        Wallet::addDelCoin($item['mobile'],$addcoin,1,'活动订单结算，活动ID：'.$id.'，订单号：'.$item['orderid']);
                    }

                    //每一百次休息一次
                    if($nums%100==0){
                        session_write_close();
                        sleep(1);
                    }
                    $nums++;
                }
            }
            Db::name('active')->where('id',$id)->update(['status'=>1]);
            return $this->ajaxSuccess('活动结算成功');
        }
    }
}